<template>
  <div id="work-box" ref="workBox">
    <h1 class="title">工作区</h1>
    <div class="main-cont mt10">
      <!-- 工具栏 -->
      <v-toolbar v-on:click="handleToolClick" style="margin: 0 0 10px 0"></v-toolbar>
      <div class="table-cont">
        <!-- 表格 -->
        <el-table :data="workspaceList"  v-loading="tableLoading" ref="table" :height="height">
          <el-table-column label="当前工作区" prop="IsCurrent" width="auto">
            <template slot-scope="scope">
              <span v-if="scope.row.IsCurrent" class="checked"></span>
            </template>
          </el-table-column>
          <el-table-column prop="Name" label="工作区名称" width="auto">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="gotoWorkspace(scope.row)"
                type="text"
                size="mini">{{ scope.row.Name }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="Id" label="工作区ID" width="auto"></el-table-column>
          <el-table-column label="设置" width="auto">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="cloneWorkspace(scope.row)"
                type="text"
                size="mini">克隆</el-button>
              <el-button
                @click.native.prevent="delWorkspace(scope.row)"
                type="text"
                size="mini">删除</el-button>
              <el-button
                @click.native.prevent="setCurrentWorkspace(scope.row)"
                type="text"
                size="mini" v-if="!scope.row.IsCurrent">设置为默认工作区</el-button>
              <el-button
                v-if="!scope.row.IsCurrent"
                @click.native.prevent="graySetting(scope.row.Id)"
                type="text"
                size="mini">灰度设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 新增/编辑弹窗 -->
    <v-dialog
    :title="editMode === 'ADD' ? '新建工作区':'克隆工作区'"
    :isVisible="editDialogShow"
    name="workDialog"
    @close="closeDialog">
      <template slot="dialog-cont">
        <el-form :model="workspaceForm" :rules="workRulesAdd" ref="workspaceForm" class="dialog-main dialogForm">
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item :label="editMode === 'ADD' ? '工作区ID' : '目标工作区ID'" prop="Id" >
                <el-input v-model="workspaceForm.Id" placeholder="请输入工作区ID"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="editMode === 'ADD' ? '工作区名称' : '目标工作区名称'" prop="Name">
                <el-input v-model="workspaceForm.Name" placeholder="请输入工作区名称"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" v-if="editMode === 'CLONE'">
            <el-col :span="12">
              <el-form-item label="源工作区ID">
                <el-input v-model="sourceId" :disabled="true"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template slot="dialog-btns">
        <div class="form-buttons">
          <el-button @click="resetForm" size="mini">重置</el-button>
          <el-button @click="closeDialog('workDialog')" size="mini">关闭</el-button>
          <el-button type="primary" @click="submitForm" size="mini">确定</el-button>
        </div>
      </template>
    </v-dialog>
    <!-- 灰度设置弹框 -->
    <v-dialog title="工作区灰度设置" :isVisible="graySShow" @close="closeDialog" name="workDialogSetting">
      <template slot="dialog-cont">
        <el-form :model="confirmPostData" ref="workspaceFormSetting" :rules="workRulesSetting">
          <el-form-item label="灰度用户组" prop="groupId">
            <el-select v-model="confirmPostData.groupId" popper-class="zIndex-popper" @change="getGroupName">
              <el-option v-for="item in groupList" :key="item.id" :label="item.groupName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-btns">
        <div class="form-buttons">
          <el-button @click="closeDialog('workDialogSetting')" size="mini">关闭</el-button>
          <el-button type="primary" @click="setGrayDialogSubmit" size="mini">确定</el-button>
        </div>
      </template>
    </v-dialog>
  </div>
</template>
<script>
import VToolbar from '../comm/iToolbar/iToolbar'
import VDialog from '../comm/iDialog/iDialog'
import rules from '../js/formRules'
import { nextPage } from '../../../assets/js'
import { mapMutations, mapState } from 'vuex'
import { mixinParams } from '../../../assets/js/iapMixin'
import api from '../../../api/url'
import ajax from '../../../api/ajax/ajax'
import sysNameObj from '../../../sysNameObj'
export default {
  name: 'workspace',
  components: {
    VToolbar,
    VDialog
  },
  mixin: [mixinParams],
  data () {
    return {
      editMode: 'ADD',
      editDialogShow: false,
      graySShow: false, // 灰度设置弹框
      // selectUserGroupName: '',
      groupList: [],
      confirmPostData: {
        workspaceId: '',
        groupId: ''
      }, // 灰度设置 确认 发送的参数
      graySetDialogData: [],
      // graySetDialogData: {
      //   createTime: '',
      //   effected: '',
      //   groupId: '',
      //   groupName: '',
      //   workspaceId: ''
      // },
      height: null,
      workspaceList: [],
      workspaceForm: {},
      workRulesAdd: rules.workRulesAdd,
      workRulesSetting: rules.workRulesSetting,
      tableLoading: true,
      sourceId: '',
      sysNameObj: sysNameObj
    }
  },
  computed: {
    ...mapState([
      'appId'
    ])
  },
  methods: {
    ...mapMutations([
      'pd_updateWorkspaceId',
      'pd_updateWorkspaceName',
      'pd_updateAppId'
    ]),
    // 工具栏操作
    handleToolClick (oprType) {
      switch (oprType) {
        case 'add':
          this.addWorkspace()
          break
        default:
          break
      }
    },
    // 获取工作区列表
    getWorkspaceList () {
      let getData = {
        AppId: this.appId
      }
      ajax.get(api.QUERY_WORKSPACE_LIST, getData).then(res => {
        if (res.Code === 0) {
          if (res.Workspaces) {
            for (let i = 0; i <= res.Workspaces.length - 1; i++) {
              if ('IsCurrent' in res.Workspaces[i]) {
                this.gotoVersionSetting(res.Workspaces[i])
                break
              }
            }
            this.workspaceList = JSON.parse(JSON.stringify(res.Workspaces))
          } else {
            this.workspaceList = []
          }
        }
        this.tableLoading = false
      })
    },
    // 从左侧菜单进入版本发布
    gotoVersionSetting (params) {
      ajax.get(api.GOTO_WORKSPACE, {id: params.Id}).then(() => {
        this.pd_updateWorkspaceId(params.Id)
        this.pd_updateWorkspaceName(params.Name)
      })
    },
    // 从工作区管理进入工作区
    gotoWorkspace (data) {
      ajax.get(api.GOTO_WORKSPACE, {id: data.Id}).then(res => {
        if (res.Code === 0) {
          // this.pd_updateWorkspaceId(data.Id)
          // this.pd_updateWorkspaceName(data.Name)
          // nextPage('/home/materialMgr')
          nextPage('/home/contentMgr')
        }
      })
    },
    // 新增工作区
    addWorkspace () {
      this.editMode = 'ADD'
      this.editDialogShow = true
    },
    // 克隆工作区
    cloneWorkspace (data) {
      this.editMode = 'CLONE'
      this.editDialogShow = true
      this.sourceId = data.Id
    },
    // 删除工作区
    delWorkspace (data) {
      this.$confirm('确定要删除该工作区吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let rmdata = {
          id: data.Id
        }
        ajax.get(api.DELETE_WORKSPACE, rmdata).then(res => {
          if (res.Code === 0) {
            this.getWorkspaceList()
            this.$message({
              type: 'success',
              message: '工作区删除成功'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 设置为当前工作区
    setCurrentWorkspace (data) {
        this.$confirm('确定要设置该工作区为当前工作区吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData = {
            Id: data.Id,
            AppId: this.AppId
          }
          ajax.post(api.SET_WORKSPACE, postData).then(res => {
            this.getWorkspaceList()
            if (res.Code === 0) {
              this.$message({
                type: 'success',
                message: '当前工作区设置成功'
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 通过下拉选择的groupId获取groupName
    getGroupName (val) {
      // let obj = {}
      // obj = this.groupList.find(item => {
      //   return item.groupId === val
      // })
      // this.confirmPostData = Object.assign(obj, {groupType: 'app'})
    },
    // 工作区管理的灰度设置的查询
    requireSetting (pageNo = 1, pageSize = 10) {
      ajax.post(api.GRAY_USER_GROUP_FILTER, {groupType: 'ws', pageNo: pageNo, pageSize: pageSize}).then(res => {
        // this.graySetDialogData = res.data.list
        // this.groupList = res.data.list.map(item => {
        //   return {groupId: item.groupId, groupName: item.groupName}
        // })
        this.groupList = res.data
      })
    },
    // 灰度设置
    graySetting (val) {
      this.confirmPostData.workspaceId = val
      this.requireSetting()
      this.graySShow = true
    },
    // 初始化表单
    initForm (name) {
      if (name === 'workDialogSetting') {
        this.confirmPostData = {}
        this.$nextTick(() => {
          this.$refs.workspaceFormSetting.clearValidate()
        })
      }
      this.$refs.workspaceForm.resetFields()
      this.workspaceForm = {}
    },
    // 重置表单域
    resetForm () {
      this.initForm()
    },
    // 关闭弹窗
    closeDialog (name) {
      this.initForm(name)
      this.editDialogShow = false
      this.graySShow = false
    },
    // 提交表单
    submitForm () {
      this.$refs.workspaceForm.validate((valid) => {
        if (valid) {
          let postData = {
            Id: this.workspaceForm.Id,
            Name: this.workspaceForm.Name,
            AppId: this.appId
          }
          if (this.editMode === 'ADD') {
            ajax.post(api.ADD_WORKSPACE, postData).then(res => {
              if (res.Code === 0) {
                this.closeDialog()
                this.getWorkspaceList()
                this.$message({
                  type: 'success',
                  message: '新工作区创建成功'
                })
              }
            })
          } else {
            postData.CloneFrom = this.sourceId
            ajax.post(api.CLONE_WORKSPACE, postData).then(res => {
              if (res.Code === 0) {
                this.closeDialog()
                this.getWorkspaceList()
                this.$message({
                  type: 'success',
                  message: '工作区克隆成功'
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 灰度设置确定
    setGrayDialogSubmit () {
      this.$refs.workspaceFormSetting.validate(valid => {
        if (valid) {
          ajax.post(api.INSERT_WORKSPACE_GROUP, this.confirmPostData).then(res => {
            this.$message({
              type: 'success',
              message: res.msg
            })
            this.graySShow = false
          })
        }
      })
    }
  },
  created () {
    // this.height = window.innerHeight - 70
    if (!this.appId) {
      let appId = sessionStorage.getItem('appId')
      this.pd_updateAppId(appId)
    }
    this.$nextTick(() => {
      this.height = this.$refs.workBox.offsetHeight - 138
      this.getWorkspaceList()
    })
  }
}
</script>
<style lang="stylus">
#work-box
  height 100%
  background #f5f5f5
  overflow hidden
  .el-aside, .el-container, .el-menu
    height 100%
  .el-menu-item
    height 35px
    line-height 35px
  // .el-menu-item
  //   &:hover
  //     background-color #4c4c4c
  .el-table--border::after,
  .el-table--group::after,
  .el-table::before
    background #fff
  .checked
    display block
    margin-left 15px
    width 32px
    height 32px
    background url('') no-repeat center center
  .title
    height 60px
    padding 15px
    line-height 30px
    font-size 18px
    font-weight normal
    background #fff
  .mt10
    margin 10px 0 0 10px
</style>
